<template>
  <div class="config-editor-layout">
    <!-- 头部工具栏 -->
    <div class="config-editor-header">
      <div class="header-left">
        <el-breadcrumb separator="/">
          <el-breadcrumb-item :to="{ path: '/configs' }">配置中心</el-breadcrumb-item>
          <el-breadcrumb-item>装备配置</el-breadcrumb-item>
        </el-breadcrumb>
        <span class="config-status" :class="validationStatus" v-if="validationResult">
          <el-icon><component :is="getValidationIcon()" /></el-icon>
          {{ getValidationText() }}
        </span>
      </div>
      <div class="header-right">
        <el-space>
          <el-button @click="validateAll" :loading="validating">
            <el-icon><Check /></el-icon>
            验证配置
          </el-button>
          <el-button @click="previewChanges" :disabled="!needsSaving">
            <el-icon><View /></el-icon>
            预览变更
          </el-button>
          <el-button type="primary" @click="saveAll" :loading="saving" :disabled="!needsSaving">
            <el-icon><Document /></el-icon>
            保存配置
          </el-button>
        </el-space>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="config-editor-main">
      <!-- 侧边栏：装备列表 -->
      <div class="config-editor-sidebar">
        <!-- 搜索和过滤 -->
        <div class="sidebar-toolbar">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索装备..."
            :prefix-icon="Search"
            clearable
            size="small"
          />
          <el-select
            v-model="filterJob"
            placeholder="职业"
            size="small"
            clearable
            style="margin-top: 8px;"
          >
            <el-option label="血骑士" value="血骑士" />
            <el-option label="圣牧师" value="圣牧师" />
            <el-option label="影刺客" value="影刺客" />
          </el-select>
          <el-select
            v-model="filterType"
            placeholder="类型"
            size="small"
            clearable
            style="margin-top: 8px;"
          >
            <el-option label="武器" value="武器" />
            <el-option label="防具" value="防具" />
            <el-option label="饰品" value="饰品" />
          </el-select>
        </div>

        <!-- 装备列表 -->
        <div class="equipment-list">
          <div class="list-header">
            <span>装备列表 ({{ filteredEquipments.length }})</span>
            <el-button 
              type="primary" 
              size="small" 
              @click="showCreateDialog = true"
              circle
            >
              <el-icon><Plus /></el-icon>
            </el-button>
          </div>
          
          <div class="equipment-items">
            <div
              v-for="equipment in filteredEquipments"
              :key="equipment.id"
              class="equipment-item"
              :class="{ active: selectedEquipmentId === equipment.id }"
              @click="selectEquipment(equipment.id)"
            >
              <div class="item-header">
                <span class="item-emoji">{{ equipment.emoji }}</span>
                <span class="item-name">{{ equipment.name }}</span>
                <el-dropdown @command="handleEquipmentAction" trigger="click">
                  <el-button size="small" text @click.stop>
                    <el-icon><MoreFilled /></el-icon>
                  </el-button>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item :command="{action: 'duplicate', id: equipment.id}">
                        复制
                      </el-dropdown-item>
                      <el-dropdown-item :command="{action: 'export', id: equipment.id}">
                        导出
                      </el-dropdown-item>
                      <el-dropdown-item 
                        :command="{action: 'delete', id: equipment.id}" 
                        divided
                      >
                        删除
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
              <div class="item-meta">
                <span class="item-job">{{ equipment.job }}</span>
                <span class="item-type">{{ equipment.type }}</span>
              </div>
              <div class="item-quality">
                品质: {{ equipment.quality.min }}-{{ equipment.quality.max }}
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 主编辑区 -->
      <div class="config-editor-content">
        <div v-if="!selectedEquipmentId" class="welcome-screen">
          <el-empty 
            description="请从左侧选择一个装备配置进行编辑，或创建新的装备配置"
            :image-size="120"
          >
            <el-button type="primary" @click="showCreateDialog = true">
              <el-icon><Plus /></el-icon>
              创建新装备
            </el-button>
          </el-empty>
        </div>

        <div v-else class="equipment-editor">
          <EquipmentForm
            :equipment="selectedEquipment"
            @update="handleEquipmentUpdate"
            @validate="handleEquipmentValidate"
          />
        </div>
      </div>
    </div>

    <!-- 创建装备对话框 -->
    <el-dialog 
      v-model="showCreateDialog" 
      title="创建新装备" 
      width="800px"
      :close-on-click-modal="false"
    >
      <EquipmentForm
        :equipment="newEquipmentTemplate"
        mode="create"
        @create="handleEquipmentCreate"
        @cancel="showCreateDialog = false"
      />
    </el-dialog>

    <!-- 预览变更对话框 -->
    <el-dialog 
      v-model="showPreviewDialog" 
      title="配置变更预览" 
      width="1000px"
    >
      <ConfigPreview
        :changes="pendingChanges"
        @confirm="confirmChanges"
        @cancel="showPreviewDialog = false"
      />
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted } from 'vue'
import { useConfigStore } from '@/stores/config'
import type { EquipmentTemplate } from '@/types/config'
import EquipmentForm from '@/components/EquipmentForm.vue'
import ConfigPreview from '@/components/ConfigPreview.vue'

// 图标导入
import { 
  Check, View, Document, Search, Plus, MoreFilled,
  CircleCheck, Warning, CircleClose 
} from '@element-plus/icons-vue'

const configStore = useConfigStore()

// 响应式数据
const searchKeyword = ref('')
const filterJob = ref('')
const filterType = ref('')
const selectedEquipmentId = ref<string>('')
const showCreateDialog = ref(false)
const showPreviewDialog = ref(false)
const validating = ref(false)
const saving = ref(false)
const pendingChanges = ref([])

// 新装备模板
const newEquipmentTemplate = ref<Partial<EquipmentTemplate>>({
  id: '',
  name: '',
  sys: '现代',
  type: '武器',
  job: '血骑士',
  solt: '主手',
  icon: '',
  emoji: '⚔️',
  quality: { min: 1, max: 5 },
  baseAttributes: [],
  skillPools: {
    inherent: [],
    enchantable: []
  },
  enabled: true
})

// 计算属性
const filteredEquipments = computed(() => {
  return configStore.filteredEquipments.filter(equipment => {
    // 搜索过滤
    if (searchKeyword.value) {
      const keyword = searchKeyword.value.toLowerCase()
      if (!equipment.name.toLowerCase().includes(keyword) &&
          !equipment.id.toLowerCase().includes(keyword)) {
        return false
      }
    }
    
    // 职业过滤
    if (filterJob.value && equipment.job !== filterJob.value) {
      return false
    }
    
    // 类型过滤
    if (filterType.value && equipment.type !== filterType.value) {
      return false
    }
    
    return true
  })
})

const selectedEquipment = computed(() => {
  return configStore.currentEquipments.find(eq => eq.id === selectedEquipmentId.value)
})

const needsSaving = computed(() => configStore.needsSaving)

const validationResult = computed(() => 
  configStore.validationResults.equipment
)

const validationStatus = computed(() => {
  if (!validationResult.value) return 'info'
  if (validationResult.value.errors.length > 0) return 'error'
  if (validationResult.value.warnings.length > 0) return 'warning'
  return 'success'
})

// 方法
const selectEquipment = (id: string) => {
  selectedEquipmentId.value = id
}

const handleEquipmentUpdate = (id: string, updates: Partial<EquipmentTemplate>) => {
  configStore.updateEquipment(id, updates)
}

const handleEquipmentValidate = async (equipment: EquipmentTemplate) => {
  // 可以在这里添加单个装备的验证逻辑
}

const handleEquipmentCreate = (equipment: EquipmentTemplate) => {
  configStore.addEquipment(equipment)
  showCreateDialog.value = false
  selectedEquipmentId.value = equipment.id
  ElMessage.success('装备创建成功')
}

const handleEquipmentAction = ({ action, id }: { action: string, id: string }) => {
  switch (action) {
    case 'duplicate':
      duplicateEquipment(id)
      break
    case 'export':
      exportEquipment(id)
      break
    case 'delete':
      deleteEquipment(id)
      break
  }
}

const duplicateEquipment = (id: string) => {
  const equipment = configStore.currentEquipments.find(eq => eq.id === id)
  if (equipment) {
    const duplicated = {
      ...equipment,
      id: `${equipment.id}_copy_${Date.now()}`,
      name: `${equipment.name} (副本)`
    }
    configStore.addEquipment(duplicated)
    selectedEquipmentId.value = duplicated.id
    ElMessage.success('装备复制成功')
  }
}

const exportEquipment = (id: string) => {
  const equipment = configStore.currentEquipments.find(eq => eq.id === id)
  if (equipment) {
    // 导出单个装备
    const blob = new Blob([JSON.stringify(equipment, null, 2)], { 
      type: 'application/json' 
    })
    const url = URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = `${equipment.name}.json`
    a.click()
    URL.revokeObjectURL(url)
  }
}

const deleteEquipment = (id: string) => {
  ElMessageBox.confirm(
    '确定要删除这个装备配置吗？此操作不可撤销。',
    '确认删除',
    {
      confirmButtonText: '删除',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    configStore.removeEquipment(id)
    if (selectedEquipmentId.value === id) {
      selectedEquipmentId.value = ''
    }
    ElMessage.success('装备删除成功')
  })
}

const validateAll = async () => {
  validating.value = true
  try {
    await configStore.validateConfigs('equipment')
    const result = validationResult.value
    if (result) {
      if (result.errors.length === 0) {
        ElMessage.success(`验证通过！检查了 ${result.validatedCount} 个配置`)
      } else {
        ElMessage.warning(`发现 ${result.errors.length} 个错误，${result.warnings.length} 个警告`)
      }
    }
  } catch (error) {
    ElMessage.error('验证失败')
  } finally {
    validating.value = false
  }
}

const previewChanges = () => {
  // 计算变更
  pendingChanges.value = []
  showPreviewDialog.value = true
}

const confirmChanges = () => {
  showPreviewDialog.value = false
  saveAll()
}

const saveAll = async () => {
  saving.value = true
  try {
    const success = await configStore.saveEquipments()
    if (success) {
      ElMessage.success('装备配置保存成功')
    } else {
      ElMessage.error('装备配置保存失败')
    }
  } catch (error) {
    ElMessage.error('装备配置保存失败')
  } finally {
    saving.value = false
  }
}

const getValidationIcon = () => {
  switch (validationStatus.value) {
    case 'success': return CircleCheck
    case 'warning': return Warning
    case 'error': return CircleClose
    default: return CircleCheck
  }
}

const getValidationText = () => {
  if (!validationResult.value) return '未验证'
  
  const { errors, warnings, validatedCount } = validationResult.value
  if (errors.length === 0 && warnings.length === 0) {
    return `验证通过 (${validatedCount}项)`
  }
  return `${errors.length}错误 ${warnings.length}警告`
}

// 监听器
watch(() => configStore.currentEquipments, (equipments) => {
  // 如果当前选中的装备不存在了，清除选择
  if (selectedEquipmentId.value && 
      !equipments.find(eq => eq.id === selectedEquipmentId.value)) {
    selectedEquipmentId.value = ''
  }
}, { deep: true })

// 生命周期
onMounted(async () => {
  await configStore.loadEquipments()
  // 自动选择第一个装备
  if (configStore.currentEquipments.length > 0 && !selectedEquipmentId.value) {
    selectedEquipmentId.value = configStore.currentEquipments[0].id
  }
})
</script>

<style scoped>
.sidebar-toolbar {
  padding: 16px;
  border-bottom: 1px solid var(--config-editor-border);
}

.equipment-list {
  flex: 1;
  overflow-y: auto;
}

.list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid var(--config-editor-border);
  font-weight: 600;
  color: var(--config-editor-text);
}

.equipment-items {
  padding: 8px;
}

.equipment-item {
  padding: 12px;
  margin-bottom: 8px;
  border: 1px solid var(--config-editor-border);
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.2s;
  background: var(--config-editor-card-bg);
}

.equipment-item:hover {
  border-color: var(--config-editor-primary);
  background: var(--config-editor-primary);
  background-opacity: 0.05;
}

.equipment-item.active {
  border-color: var(--config-editor-primary);
  background: var(--config-editor-primary);
  background-opacity: 0.1;
}

.item-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
}

.item-emoji {
  font-size: 16px;
}

.item-name {
  flex: 1;
  font-weight: 500;
  color: var(--config-editor-text);
  font-size: 14px;
}

.item-meta {
  display: flex;
  gap: 8px;
  margin-bottom: 4px;
}

.item-job, .item-type {
  padding: 2px 6px;
  background: var(--config-editor-border);
  border-radius: 4px;
  font-size: 12px;
  color: var(--config-editor-text-secondary);
}

.item-quality {
  font-size: 12px;
  color: var(--config-editor-text-secondary);
}

.welcome-screen {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
}

.equipment-editor {
  height: 100%;
  overflow-y: auto;
  padding: 20px;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.header-right {
  display: flex;
  align-items: center;
}
</style>
